#include "filesListTab.h"
#include "../core/Pkg.h"

#include <QWidget>
#include <QLabel>
#include <QString>
#include <QColor>

FilesListTab::FilesListTab(){
//setMaximumHeight(100); //da mettere piu flessibile
  filesList = new KTextEdit();
  filesList->setReadOnly(true);
  layout = new QVBoxLayout(this);
  setLayout(layout);
  layout->addWidget(filesList);
  QString text;
  text.sprintf("<br><html><head><syle type='text/css'/> </head><body><h3><center>Select a package to get files list and usage statistics.</center><br></h3></body></html>");
  filesList->clear();
  filesList->append(text);
  filesList->moveCursor(QTextCursor::Start);
}

FilesListTab::~FilesListTab() {
}
void FilesListTab::setFiles(vector<FileObj> fobj,time_t tm) {
// setta l'elenco dei files nel KTextEdit
  QString text;
  text.sprintf("<html><head><syle type='text/css'/> </head><body><h3>Package installs %d files in your system.<br>", fobj.size());
  if(tm==-1) text.append("Last access time is unavailable.</h3><h4> <table>");
  text.append("Last access date of the entire package is " + QString(TimeDiff(tm, 'D').c_str()) + ".</h3><h4> <table>"); //qua ho piazzato il printf xke' ci sta bene un "titolo" con il last use in formato data e giorni
  for (int i = 0; i < fobj.size(); i++) {
    QString fileName = QString(fobj[i].name.c_str());
    QString date = QString(TimeDiff(fobj[i].tm, 'D').c_str());
    if(fobj[i].enabled=='Y') text.append("<tr><td>" + fileName + "</td><td width='15'/><td> " + date + "</td></tr>"); 
    else if(fobj[i].enabled=='D') text.append("<tr><td><i><font color='#989898'>" + fileName + "</font></i></td><td width='15'/><td><font color='#989898'> directory </font></td></tr>"); 
    else if(fobj[i].enabled=='F') text.append("<tr><td><i><font color='#989898'>" + fileName + "</font></i></td><td width='15'/><td><font color='#989898'> filtered </font> </td></tr>");
    else if(fobj[i].enabled=='N') text.append("<tr><td><i><font color='#989898'>" + fileName + "</font></i></td><td width='15'/><td><font color='#989898'> not found </font></td></tr>"); 
  }
  text.append("</h4></table></body></html>");
  filesList->clear();
  filesList->append(text);
  filesList->moveCursor(QTextCursor::Start);
}

string FilesListTab::TimeDiff(time_t file_tm, const char m) {
// formatta la data /* d days, S sentence, D date */
  string toret;
  char timestr[100];
  time_t now;
  time(&now);
  double dif = difftime(now, file_tm);

  if (m == 'd') {
    sprintf(timestr, "%.0f", ceil(dif / (60 * 60 * 24)));
    toret = timestr;
  } 
  else if (m == 'D') {
    struct tm* atime = localtime(&file_tm);
    strftime(timestr, 100, "%Y-%m-%d", atime); //%X per l'ora esatta :D
    toret = timestr;
  }
  return toret;
}
